package com.example.redisdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {  
	@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(connectionFactory);
		// 设置key和value的序列化方式

		// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
		Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
		template.setValueSerializer(serializer);

		//设置key的序列化器为StringRedisSerializer
		template.setKeySerializer(new StringRedisSerializer());

		// 设置value的序列化器为JdkSerializationRedisSerializer
		template.setHashKeySerializer(new StringRedisSerializer());

		// 设置hash的value的序列化器为Jackson2JsonRedisSerializer
		template.setHashValueSerializer(serializer);
		return template;
	}
}
